package org.diysearch.tools;

import java.io.FileWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.configuration.INIConfiguration;
import org.apache.commons.lang.StringUtils;

import org.diysearch.interfaces.TemplateEngine;

public class ModelMaker {
	private static final String DEF_FILE = "/models-def.ini";
	private static final String MODEL_TEMPLATE = "system/model-maker.ftl";
	private static final String SOURCE_HOME = "c:/dpalmer/Eclipse-Development/workspace/Sanctuary/src";
	
	public static void main(String[] args) throws Exception {
		INIConfiguration config = new INIConfiguration();
		config.load(ModelMaker.class.getResourceAsStream(DEF_FILE));
		System.out.println("Creating models defined in: " + DEF_FILE);

		for (Object sec : config.getSections().toArray()) {
			TemplateEngine te = (TemplateEngine) BaseTool.IOC_ENGINE.getBean("templateEngine");
			StringUtils su = new StringUtils();
			te.setContent("stringUtils",su);
			
			String section = (String) sec;
			System.out.println("Building: " + section);
			Map<String,Object> content = new HashMap<String,Object>();
			content.put("className",section);
			content.put("package", config.getString(section+".package"));
			content.put("aliasName", config.getString(section+".aliasName"));
			String fields = config.getString(section+".fields");
			
			String[] _f = fields.split("\\|");
			List<Map<String,String>> fieldDefs = new ArrayList<Map<String,String>>();
			
			for (String _field : _f) {
				String[] parts = _field.split(":");
				String _type = parts[0];
				String _name = parts[1];
				Map<String,String> _def = new HashMap<String,String>();
				_def.put("name", _name);
				_def.put("type", _type);
				fieldDefs.add(_def);
			}
			
			content.put("fields",fieldDefs);
			String packageSrc = config.getString(section+".package").replaceAll("\\.", "\\/");
			StringWriter sw = (StringWriter) te.getContent(MODEL_TEMPLATE, content);
			FileWriter fw = new FileWriter(SOURCE_HOME+"/"+packageSrc+"/"+section+".java");
			fw.write(sw.toString());
			fw.flush();
			fw.close();
		}
		
	}

}
